package com.fjbdxk.beidou.net;

import com.fazecast.jSerialComm.SerialPort;
import com.fjbdxk.beidou.core.AbstractBeiDouMessage;
import com.fjbdxk.beidou.core.AbstractBeiDouNet;
import com.fjbdxk.beidou.msg.BDFKIMessage;

import java.io.InputStream;
import java.io.OutputStream;

/**
 * 串口通信
 *
 * @author huanggy
 * @version 1.0.0
 * @date 2024/05/13
 **/
public class SerialBeiDouNet extends AbstractBeiDouNet {

    // 串口号
    private String portDescriptor = "COM4";
    // 波特率
    private int baudRate = 115200;
    // 串口
    private SerialPort serialPort;

    public SerialBeiDouNet() {

    }

    public SerialBeiDouNet(String portDescriptor, int baudRate) {
        this.portDescriptor = portDescriptor;
        this.baudRate = baudRate;
    }


    @Override
    public boolean open() {
        if (serialPort == null) {
            serialPort = SerialPort.getCommPort(portDescriptor);
            serialPort.setBaudRate(baudRate);
            return serialPort.openPort();
        } else {
            return true;
        }
    }

    @Override
    public boolean close() {
        if (serialPort == null) {
            return true;
        } else {
            return serialPort.closePort();
        }
    }

    @Override
    public String doSend(AbstractBeiDouMessage message) {
        InputStream inputStream = serialPort.getInputStream();
        OutputStream outputStream = serialPort.getOutputStream();
        try {
            outputStream.write(message.getMshByte());
            // 休眠一会
            Thread.sleep(100);

            byte[] buffer = new byte[1024];
            int len = inputStream.read(buffer);
            if (len > 0) {
                String receivedMessage = new String(buffer, 0, len);

                System.out.println(receivedMessage);

                return receivedMessage;
            } else {
                // 没有读取到消息，反馈null
                return null;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
